//GENERAL PAGES FUNCTIONS //
var pageType;
//CARGA LA PAGINA SELECCIONADA DEL MENU
$('.page.active').live("click", function() {
	pageType = $(this).attr("data-page");
	var page = $(this).attr('id');
	$('.page').removeClass('on');
	$(this).addClass('on');	
		
	$.ajax({
	    type: 'POST',
	    dataType: "text", //lets specify that we will return data as TEXT                  
	    url: "ajax/page/load.htm",
	    data:{pageId:page},
	    success: function(data) {
	    $('.content').html(data);
	    if(pageType == "dataType"){
	 	    initDataType();
	    }
	    if(pageType == "archive"){
	    	initArchive();
	    }
	    
	    if(pageType == "imageGal"){
	    	initImageGal();
	    }
	    
	    if(pageType == "catalog"){
	    	initCatalog();
	    }
	    
	    if(pageType == "videoGal"){
	    	initVideoGal();
	    }
	    
	    },
	    error: function() {
	    	//handle error here
	    }
	});
	
	return false;
});

//SELECTOR DE LAYOUT
$('#page_templates').find('input').live("click", function() {
			$(this).parent().parent().find('li').removeClass('active');
			$(this).parent().addClass('active');
			setNewPageTemplate($(this).parent().attr("data-template"));

});
$('#page_templates ul li img').live("click", function() {
			$(this).parent().parent().find('li').removeClass('active');
			$(this).parent().addClass('active');
			$(this).parent().parent().find('input').attr('checked', false);
			$(this).parent().find('input').attr('checked', true);
			setNewPageTemplate($(this).parent().attr("data-template"));
});

//SELECCIONA UN NUEVO TEMPLATE
function setNewPageTemplate(template){
	var pageId = $('#pageInfo').attr("data-pageId");
	pageType = $('#pageInfo').attr("data-pageType");
	sendUrl = "ajax/Pagetemplate.htm";
	$.ajax({
	    type: 'POST',
	    dataType: "text",                 
	    url: sendUrl,
	    data: {'template': template,'pageId':pageId},
	    success:function(data) {   
	    	$('.content').html(data);
	    	if(pageType == "dataType"){
	 	    initDataType();
	    	}
	    },
	    error: function() {
	    	//handle error here
	    }
	});
}


//-----------------------DATATYPE (TEXTO/FOTO) FUNCTIONS-------------------------------------- //
var dataTypeTemplate;

//REALIZA LA CARGA DE EVENTOS CUANDO SE RECARGA LA PAGINA
function initDataType(){
	  //FILE UPLOAD
	  $('.fileupload').each(function () {
	    	uploadImage(this);
	    });
	   //TABS DE LAS ZONAS
	    $('.nav-tabs a').live("click", function (e) {
		  	  e.preventDefault();
		  	  jQuery(this).tab('show');
		  	});
	    //INPUTS DEL FORM
	    $( ".dataTypeForm" ).blur(function() {
	    	submitDataType(this);
	    	});
	    //NUEVA ZONA
	    $("#zone_add").click(function() {
	    	addNewDataType();
	    });
	    //REMOVER ZONA
	    $('#removeZone').live("click", function (e) {
	    	$(".modal-backdrop").remove();
	    	 var id = $('.tab-pane.active').find('input[name="id"]').attr("value");
	    	 deleteDataType(id);
		  	});
	    
	   
	  //datatype templates modal functions

	  $('#page_templates_dataType').find('input').live("click", function() {
	  	dataTypeTemplate = this;
	  	$("#modal_dataType").modal('show');
	  	
	  });
	  $('#page_templates_dataType ul li img').live("click", function() {
	  	dataTypeTemplate = this;
	  	$("#modal_dataType").modal('show');
	  	
	  });

	  $('#dataTypeRemove').live("click", function (e) {
	  	$(".modal-backdrop").remove();
	  	changeDataTypeTemplate();
	    	});
}


function changeDataTypeTemplate(){
	$(dataTypeTemplate).parent().parent().find('li').removeClass('active');
	$(dataTypeTemplate).parent().addClass('active');
	if($(dataTypeTemplate).prop("tagName") == "IMG"){
	$(dataTypeTemplate).parent().parent().find('input').attr('checked', false);
	$(dataTypeTemplate).parent().find('input').attr('checked', true);
	}
	setNewPageTemplate($(dataTypeTemplate).parent().attr("data-template"));
}

//AGREGA UNA NUEVA ZONA
function addNewDataType(){
	var pageId = $('#pageInfo').attr("data-pageId");
	sendUrl = "ajax/addDataType.htm";
	$.ajax({
	    type: 'POST',
	    dataType: "text",                 
	    url: sendUrl,
	    data: {'pageId':pageId},
	    success:function(data) { 
	      $('.content').html(data);
	     initDataType();
	    },
	    error: function() {
	    	//handle error here
	    }
	});
}

//ELIMINA UNA ZONA
function deleteDataType(id) {
	
	var pageId = $('#pageInfo').attr("data-pageId");
	sendUrl = "ajax/removeDataType.htm";
	$.ajax({
			        type: "POST",
			        dataType: "text",
			        url: sendUrl,
			        data: {'dataTypeId': id,'pageId':pageId},
			        success: function(data){
			        	$('.content').html(data);
				 	    initDataType();
			        
			        },
			        error: function(e){
			       
			        }
			        });
			        
}

//ACTUALIZA LA DATA(FORM)DE UNA ZONA
function submitDataType(obj) {
	var form = $(obj).closest("form");
	var str = $(form).serialize();
	sendUrl = "ajax/dataType.htm";
	$.ajax({
			        type: "POST",
			        dataType: "text",
			        url: sendUrl,
			        data: str,
			        success: function(response){
			        // we have the response
			        
			        },
			        error: function(e){		   
			        alert('Error: ' + e);
			        }
			        });
			        
}

//-----------------------ARCHIVE (BLOG) FUNCTIONS-------------------------------------- //
var btnArchive;
//REALIZA LA CARGA DE EVENTOS CUANDO SE RECARGA LA PAGINA
function initArchive(){
	
	//MUESTRA EL FORM
	  $("#create_new_post").click(function() {
		  $("#upload_post").css("display", "block");
	  });
	  
	    
	   //FILE UPLOAD
		$('.fileupload').each(function () {
		    	uploadImage(this);
		});
		
	    
	  //remove archive modal functions
	   
	    $('button.archive.remove').live("click", function(){
	    	btnArchive = this;	    
	    	$("#modal_archive").modal('show');
	    	
	    });
	    
	    $('#archiveRemove').live("click", function (e) {
	    	$(".modal-backdrop").remove();
	    	var id = $(btnArchive).attr("data-itemId");
	    	deleteArchive(id);
	      	});
	    
	    //edit archive data
	    $('button.archive.edit').live("click", function(){
	  	  $("#upload_post").css("display", "block");
	  	  loadArchiveFormData(this);
	    	
	    });
	  
}

//ACTUALIZA LA DATA(FORM)DE UN ARCHIVE (BLOG)
function 	updateArchiveData(form,cropJson,uploaderID){
	var str = $(form).serialize();
	sendUrl = "ajax/updateArchive.htm";
	$.ajax({
			        type: "POST",
			        dataType: "json",
			        url: sendUrl,
			        data: str,
			        success: function(response){
			        	refreshFormData(form);
						$("#uploaded-files_"+uploaderID).empty();
						$("#imageContainer_"+uploaderID).removeClass('editing');		
						var tr = $("#archive_"+response.id);
						$(tr).find('td.text').text(response.title);
						 $("#upload_post").css("display", "none");
			        
			        },
			        error: function(e){
			        
			        alert('Error: ' + e);
			        }
			        });
			        
}
//carga la data del formulario para ser editado
function loadArchiveFormData(obj){
    var id = $(obj).attr('data-itemId');
    var uploaderID = $(obj).attr('data-uploaderid');
    $("#imageContainer_"+uploaderID).addClass('editing');
    var form = $("#imageForm_archive1");
    refreshFormData(form);
    $("#uploaded-files_"+uploaderID).empty();
    sendUrl = "ajax/loadArchive.htm";
    $.ajax({
        type: "POST",
        dataType: "json",
        url: sendUrl,
        data: {'archiveId': id},
        success: function(data){
        	var form = $("#imageForm_archive1");
            $(form).find('input#title').val(data.title);
            document.getElementById("archive_text").value=data.text;
            $(form).find('input#tags').val(data.tags);	
            $(form).find('input#video_url').val(data.video_url);
            $(form).find('input#id').val(data.id);
            $("#uploaded-files_"+uploaderID).html("");
            $("#uploaded-files_"+uploaderID).append($('<div id="actual_img_'+uploaderID+'" class="actual_img" ><img width="100%"  src="'+data.src+'" style="display: block; visibility: visible; width: 400px; height: auto;" /></div>'));      
            $("#archive_ub").text("CAMBIAR IMAGEN");
        },
        error: function(e){
        
        alert('Error: ' + e);
        }
        });
    

}

function refreshArchiveFormData(form){
	
	$(form).find('input#title').val("");
	document.getElementById("archive_text").value="";
	$(form).find('input#tags').val("");
	$(form).find('input#video_url').val("");
}


//ELIMINA UN ARCHIVE
function deleteArchive(id) {
	
	var pageId = $('#pageInfo').attr("data-pageId");
	sendUrl = "ajax/removeArchive.htm";
	$.ajax({
			        type: "POST",
			        dataType: "text",
			        url: sendUrl,
			        data: {'archiveId': id,'pageId':pageId},
			        success: function(data){
			        	$('.content').html(data);
				 	    initArchive();
			        
			        },
			        error: function(e){
			       
			        }
			        });
			        
}

//move archive down
$('.archive_down').live("click", function(){
	
	     var row = $(this).closest('tr')[0];
	     
	     if ($(row).next()){
	    	 var _id1 = $(row).attr('id');
			 var _position1 = $(row).index()+2;
			 var _id2 = $(row).next().attr('id');
			 var _position2 = $(row).next().index();
			 
			 $(row).insertAfter($(row).next());

			 updateArchivePosition(_id1,_position1,_id2,_position2);
	     
          }	     
	    
	 });
	 	
//move archive up
$('.archive_up').live("click", function(){
	
	 var row = $(this).closest('tr')[0];
	 
	    if ($(row).prev()){
	    	
	    	var _id1 = $(row).attr('id');
			var _position1 = $(row).index();
			var _id2 = $(row).prev().attr('id');
			var _position2 = $(row).prev().index()+2;
			 
			$(row).insertBefore($(row).prev());
			 
			updateArchivePosition(_id1,_position1,_id2,_position2); 
				
	        
	    }
			
	});


function updateArchivePosition(_id1,_position1,_id2,_position2){
	var dataJson  = new Object();
		dataJson.id1 = _id1;
		dataJson.pos1 = _position1;
		dataJson.id2 = _id2;
		dataJson.pos2 = _position2;
	    
		var jsonString = "["+JSON.stringify(dataJson)+"]";
		var postData =  {Data:jsonString};
		var sendUrl = "ajax/updateArchivePosition.htm";
		$.ajax({
		    type: 'POST',
		    context:this,
		    dataType: "text",                  
		    url: sendUrl,
		    data: postData,
		    success:function(data){},
		    error: function() {
		    	//handle error here
		    }
		});
}

function succesArchiveCrop(data,uploaderID){
	
	if(data.newArchive){
		$("#archive_table_"+uploaderID).append($('<tr/>',{'id':'archive_'+data.id+''}).append($('<td/>').append($('<img/>',{'src':'/userimages/'+data.image,'class':'gallery_image'})))
			       .append($('<td class="text" />').text(data.title))
			       .append($('<td class="icon" />').append($('<button/>',{'class':'btn info alternative icon archive edit','data-uploaderid':''+uploaderID+'','data-itemid':''+data.id+''})))
				   .append($('<td class="icon" />').append($('<button/>',{'class':'btn danger alternative icon archive remove','data-uploaderid':''+uploaderID+'','data-itemid':''+data.id+''})))		
	               .append($('<td class="icon" />').append($('<div class="editImage"><span><img class="archive_up" src="css/images/arrow-up.png"/><img class="archive_down" src="css/images/arrow-down.png"/></span></div>'))));
	}else{
	
	 $("#archive_"+data.id).find('img:first').attr("src","/userimages/"+data.image);
	 $("#upload_post").css("display", "none");
	}
}

//-----------------------IMAGE GALLERY FUNCTIONS-----------------------------------------------------//

function initImageGal(){
	
	 //FILE UPLOAD
	$('.fileupload').each(function () {
	    	uploadImage(this);
	});
	
	$('#create_new_gallery_picture').click(function () {
	    	$('#upload_gallery_picture').show();
	});
	
	$('#createGalButton').click(function () {
		 addNewImageGal();
     });
	
	$( "#galleries" ).change(function() {
		$("#gallery_edit_section").css("display","block");
		var id = $( "#galleries option:selected" ).val();
		loadGalleryData(id);
		});
	
}
	
	//ADD NEW IMAGE GALLERY
	function addNewImageGal(){
		var pageId = $('#pageInfo').attr("data-pageId");
		var name = $('#new_galery_name').val();
		var description = $('#new_galery_description').val();
		sendUrl = "ajax/addImageGallery.htm";
		$.ajax({
		    type: 'POST',
		    dataType: "json",                 
		    url: sendUrl,
		    data: {'pageId':pageId,'name':name,'description':description},
		    success:function(data) { 
		      $("#new_galery_modal").modal('hide');
		      var $gals = $("#galleries");
		      $gals.empty(); // remove old options
		      $.each(data, function(key, value) {
		       $gals.append($("<option></option>").attr("value", value.id).text(value.name));
		      });
		      initImageGal();
		    },
		    error: function() {
		    	//handle error here
		    }
		});
	}
	
	//LOAD GALLERY DATA FOR EDITING
	function loadGalleryData(id){
		sendUrl = "ajax/getImageGallery.htm";
		$.ajax({
		    type: 'POST',
		    dataType: "json",                 
		    url: sendUrl,
		    data: {'galleryId':id},
		    success:function(data) { 
		    $("#edit_gallery_name").val(data[0].name);
		    $("#edit_gallery_description").text(data[0].description);
		    },
		    error: function (request, status, error) {
		        alert(status);
		    }
		});
	}
	

//-----------------------CATALOG (Catalogo de items) FUNCTIONS-------------------------------------- //

//REALIZA LA CARGA DE EVENTOS CUANDO SE RECARGA LA PAGINA
function initCatalog(){
	
	//muestra el crear item
	$('#create_new_item').live("click", function(){
		$('#new_items').toggle();
	});	
	    
	
}



//-----------------------VIDEOGAL (GALERIA DE VIDEOS) FUNCTIONS-------------------------------------- //

//REALIZA LA CARGA DE EVENTOS CUANDO SE RECARGA LA PAGINA
function initVideoGal(){
	
	//Funcion que busca los videos en youtube
	function loadVideosJsonYouTube(channelName) {
	  	
	  	$.getJSON('https://gdata.youtube.com/feeds/api/users/'+channelName+'/uploads?alt=json', function(jsonData) {   		
   			$(jsonData.feed.entry).each(function(){
   				$("#json_videos_list").append("<tr id='"+this.id.$t+"'><td><img class='gallery_image' src='"+this.media$group.media$thumbnail[1].url+"'></td><td class='text'>"+this.title.$t+"</td><td class='icon'><select class='form-control'><option>Oculto</option><option>Visible</option></select></td><td class='icon'><div class='editImage'><span><img class='archive_up' src='css/images/arrow-up.png'/><img class='archive_down' src='css/images/arrow-down.png'/></span></div></td></tr>");
			});//fin del each
		});
		
	}
	
	$('#youtube_user').live("click", function(){
		loadVideosJsonYouTube($('#youtube_user_input').val());
	});
	
		//Funcion que busca los videos en youtube
	function loadVideosJsonVimeo(channelName) {
	  	
	  	$.getJSON('http://vimeo.com/api/v2/'+channelName+'/videos.json', function(jsonData) {   		
   			$(jsonData).each(function(){
   				$("#json_videos_list").append("<tr id='"+this.id+"'><td><img class='gallery_image' src='"+this.thumbnail_small+"'></td><td class='text'>"+this.title+"</td><td class='icon'><select class='form-control'><option>Oculto</option><option>Visible</option></select></td><td class='icon'><div class='editImage'><span><img class='archive_up' src='css/images/arrow-up.png'/><img class='archive_down' src='css/images/arrow-down.png'/></span></div></td></tr>");
			});//fin del each
		});
		
	}
	
	$('#vimeo_user').live("click", function(){
		loadVideosJsonVimeo($('#vimeo_user_input').val());
	});	
	    
	
}


